package com.example.demo.solon.filter;

import io.vertx.core.buffer.Buffer;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.text.StrUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.cloud.gateway.exchange.ExContext;
import org.noear.solon.cloud.gateway.exchange.ExFilter;
import org.noear.solon.cloud.gateway.exchange.ExFilterChain;
import org.noear.solon.cloud.gateway.route.RouteFilterFactory;
import org.noear.solon.rx.Completable;

/**
 * @author airhead
 */
@Component
@Slf4j
public class AuthFilterFactory implements RouteFilterFactory {
  public static final String TOKEN = "token";
  public static final String EMPTY = "empty";

  @Override
  public String prefix() {
    return "Auth";
  }

  @Override
  public ExFilter create(String config) {
    if (TOKEN.equals(config)) {
      return new TokenFilter();
    } else {
      return new EmptyAuthFilter();
    }
  }

  /** 默认的空鉴权 */
  public static class EmptyAuthFilter implements ExFilter {
    public EmptyAuthFilter() {}

    @Override
    public Completable doFilter(ExContext ctx, ExFilterChain chain) {
      log.info("empty filter, do nothing");

      return chain.doFilter(ctx);
    }
  }

  /** token 鉴权 ，如果鉴权逻辑比较复杂的，用独立类 */
  public static class TokenFilter implements ExFilter {
    @Override
    public Completable doFilter(ExContext ctx, ExFilterChain chain) {
      String token = ctx.rawHeader("token");
      if (StrUtil.isBlank(token)) {
        ctx.newResponse().status(401);
        ctx.newResponse().body(Buffer.buffer("token is empty"));
        return Completable.complete();
      }

      return chain.doFilter(ctx);
    }
  }
}
